/**
 * tH Array -- excel表头
 * fV Array -- 过滤数据的key
 * list Array -- 表格渲染的数据
 * fileName -- 导出excel的名称
 * formatJsonFun function -- 过滤数据的方法
 */
import Vue from 'vue'
export function exportExcel(tH, fV, list, formatJsonFun, fileName = 'excel-list') {
  const loading = Vue.prototype.$loading({
    lock: true,
    text: '导出时间较长,请耐心等待^.^',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.5)'
  })
  return new Promise((resolve, reject) => {
    import('@/vendor/Export2Excel').then(excel => {
      const tHeader = tH
      const filterVal = fV
      let data = []
      if (formatJsonFun && typeof (formatJsonFun) === 'function') {
        data = formatJsonFun(filterVal, list)
      } else {
        data = formatJson(filterVal, list)
      }
      excel.export_json_to_excel({
        header: tHeader,
        data,
        filename: fileName,
        autoWidth: true,
        bookType: 'xlsx'
      })
      loading.close()
      resolve()
    })
  })
}

function formatJson(filterVal, jsonData) {
  return jsonData.map(v => filterVal.map(j => {
    return v[j]
  }))
}
